package com.mf.morefun.ui.dohomework;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.AliInfoBean;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.PMUserBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.bean.ShareBean;
import com.mf.morefun.receiver.NetUtil;
import com.mf.morefun.requestbean.RequestSaveVideoBean;
import com.mf.morefun.requestbean.RequestShareBean;
import com.mf.morefun.ui.moreread.ListenRecordActivity;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.SendStarOrFlowerNet;
import com.mf.morefun.util.UploadUtil;
import com.mf.morefun.widget.BackIdeaPop;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.zhcx.zhcxlibrary.commenplayer.CommenPlayer;
import com.zhcx.zhcxlibrary.commenplayer.listener.IPlayerListener;
import com.zhcx.zhcxlibrary.commenplayer.listener.OnNetListener;
import com.zhcx.zhcxlibrary.commenplayer.ui.ControlLayout;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * 创作  添加视频
 */
public class LiteraryCreationActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.iv_delete)
    ImageView ivDelete;
    @BindView(R.id.iv_sure)
    ImageView ivSure;
    @BindView(R.id.edit_title)
    EditText editTitle;
    @BindView(R.id.edit_require)
    EditText editRequire;
    @BindView(R.id.player)
    CommenPlayer player;
    @BindView(R.id.iv_normal)
    ImageView ivNormal;
    @BindView(R.id.ly_content)
    LinearLayout lyContent;
    private String title = "";
    private String description = "";
    private boolean ignoreNet;
    private String videoPath = "";
    private SPUtils mSPutils;
    private String videoName = "";
    private RoundProcessDialog dialog;
    private SendStarOrFlowerNet mSendStartOrFlowerNet;
    private String userId = "";


    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_literarycreation;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        //清空缓存
        File file = new File(getBasePath());

        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files)
        {
            f.delete();
        }

        userId = getIntent().getStringExtra(com.mf.morefun.constant.Configuration.USERID);

        mSPutils = new SPUtils(getApplicationContext());
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSPutils.getString(com.mf.morefun.constant.Configuration.USERPHONE), mSPutils.getString(com.mf.morefun.constant.Configuration.USERPASSWORD));
        }
        EventBus.getDefault().register(this);
        dialog = new RoundProcessDialog(LiteraryCreationActivity.this, "正在上传...");
        title = getIntent().getStringExtra("TITLE");
        description = getIntent().getStringExtra("DESCRIPTION");
        if (!StringUtils.isEmpty(title)) {
            editTitle.setText(title);
        }
        if (!StringUtils.isEmpty(description)) {
            editRequire.setText(description);
        }
        ivNormal.setVisibility(View.VISIBLE);
        player.setVisibility(View.GONE);
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("POSTVIDEO");
        registerReceiver(mReceiver, mFilter);

        initGetAliInfo();
    }

    public String getBasePath() {
        String strPath = null;
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            strPath = getApplicationContext().getFilesDir() + "/" + "lameMp3";
        } else {
            strPath = Environment.getExternalStorageDirectory() + "/" + "lameMp3";
        }
        File dir = new File(strPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return strPath;
    }

    private void initGetAliInfo() {
        RequestParams params = new RequestParams(com.mf.morefun.constant.Configuration.HOST + com.mf.morefun.constant.Configuration.GETALIINFOV2);

        PMUserBean.CountryBean countrybean = new PMUserBean.CountryBean();
        countrybean.setId( MoreFunApplication.loginBean.getResult().getCountry().getId());
        params.setBodyContent(JSON.toJSONString(countrybean));

     /*   params.setBodyContent("{\n" +
                " \n" +
                "}");*/

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    AliInfoBean aliInfoBean = JSON.parseObject(result, AliInfoBean.class);
                    if (aliInfoBean.getStatusCode() == 200) {
                        mSPutils.putString(com.mf.morefun.constant.Configuration.ACCESSKEYID, aliInfoBean.getAccessKeyId());
                        mSPutils.putString(com.mf.morefun.constant.Configuration.ACCESSKEYSECRET, aliInfoBean.getAccessKeySecret());
                        mSPutils.putString(com.mf.morefun.constant.Configuration.SECURITYTOKEN, aliInfoBean.getSecurityToken());

                        mSPutils.putString(com.mf.morefun.constant.Configuration.ENDPOINT, aliInfoBean.getEndPoint());
                        mSPutils.putString(com.mf.morefun.constant.Configuration.BUCKETNAME, aliInfoBean.getBucketName());
                        mSPutils.putString(com.mf.morefun.constant.Configuration.BUCKETDOMAIN, aliInfoBean.getBucketDomain());


                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("POSTVIDEO")){
                if (!StringUtils.isEmpty(videoPath) && !StringUtils.isEmpty(videoName)) {
                    if (null != dialog && !dialog.isShow()) {
                        dialog.show();
                    }
                    UploadUtil uploadUtil = new UploadUtil();
                    uploadUtil.uploadFile(LiteraryCreationActivity.this,
                            mSPutils.getString(com.mf.morefun.constant.Configuration.ACCESSKEYID),
                            mSPutils.getString(com.mf.morefun.constant.Configuration.ACCESSKEYSECRET),
                            mSPutils.getString(com.mf.morefun.constant.Configuration.SECURITYTOKEN),
                            mSPutils.getString(com.mf.morefun.constant.Configuration.ENDPOINT),
                            mSPutils.getString(com.mf.morefun.constant.Configuration.BUCKETNAME),
                            "android" + videoName + ".mp4",
                            videoPath, false);
                }
            }
        }
    };

    @Override
    protected void initData() {

    }

    @OnClick({R.id.iv_back, R.id.iv_add, R.id.iv_delete, R.id.iv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_add:
                Intent intent = null;
                if (DeviceUtils.getPhoneBrand().contains("meizu")) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                } else {
                    intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(intent, 0);
                break;
            case R.id.iv_delete:
                ivNormal.setVisibility(View.VISIBLE);
                player.setVisibility(View.GONE);
                videoPath = "";
                if (null != player) {
                    player.pause();
                }
                break;
            case R.id.iv_sure:
                //
                BackIdeaPop backIdeaPop = new BackIdeaPop(LiteraryCreationActivity.this);
                backIdeaPop.showPop("确定提交该创作作业吗？", 7, 0);
                break;
        }
    }

    //接受RecordMusicService发过来的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicMessage(EventMessageBean message) {
        if (message.getType() == 101) {

            String host =  mSPutils.getString(com.mf.morefun.constant.Configuration.BUCKETDOMAIN);
            //开始上传
            initSaveVideo(host + message.getFileName());
            videoPath = host + message.getFileName();
        } else if (message.getType() == 102) {
            ToastUtils.show(getApplicationContext(), "上传失败", 100);
        }else if(message.getType() == 1099){
            try {
                showFinishPop(message.getFileName(), message.getType());
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(message.getType() == 1088){
            try {
                showFinishPop(message.getFileName(), message.getType());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (null != dialog && dialog.isShow()) {
            dialog.cancel();
        }
    }

    private void initSaveVideo(String videoPaths) {
        RequestParams params = new RequestParams(com.mf.morefun.constant.Configuration.HOST + com.mf.morefun.constant.Configuration.SAVEVIDEO);
        RequestSaveVideoBean requestSaveVideoBean = new RequestSaveVideoBean();
        requestSaveVideoBean.setAudio(videoPaths);
        requestSaveVideoBean.setType("5");
        if (StringUtils.isEmpty(getIntent().getStringExtra("TPBUS"))) {
            requestSaveVideoBean.setTpBus("");
        } else {
            requestSaveVideoBean.setTpBus(getIntent().getStringExtra("TPBUS"));
        }
        RequestSaveVideoBean.TpDetailBean tpDetailBean = new RequestSaveVideoBean.TpDetailBean();
        if (StringUtils.isEmpty(getIntent().getStringExtra("TPDETAILID"))) {
            tpDetailBean.setId("");
        } else {
            tpDetailBean.setId(getIntent().getStringExtra("TPDETAILID"));
        }
        requestSaveVideoBean.setTpDetail(tpDetailBean);
        RequestSaveVideoBean.UserBean userBean = new RequestSaveVideoBean.UserBean();
        userBean.setId(userId);
        requestSaveVideoBean.setUser(userBean);
        RequestSaveVideoBean.ClassBelongBean classBelongBean = new RequestSaveVideoBean.ClassBelongBean();
        classBelongBean.setId(getIntent().getStringExtra("CLASSID"));
        requestSaveVideoBean.setClassBelong(classBelongBean);
        RequestSaveVideoBean.TpBean tpBean = new RequestSaveVideoBean.TpBean();
        tpBean.setId(getIntent().getStringExtra("TP"));
        requestSaveVideoBean.setTp(tpBean);
        params.setBodyContent(JSON.toJSONString(requestSaveVideoBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        videoPath = "";
                        if (!StringUtils.isEmpty(getIntent().getStringExtra("BOOKID"))) {
                            mSendStartOrFlowerNet = new SendStarOrFlowerNet(LiteraryCreationActivity.this, lyContent);
                            mSendStartOrFlowerNet.initGetFlower(30
                                    , mSPutils.getString(com.mf.morefun.constant.Configuration.USERID),
                                    getIntent().getStringExtra("BOOKID"),
                                    "1", "2"
                            );
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(LiteraryCreationActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

    private PopupWindow mUserPop;

    private void showFinishPop(String message, int type) {
        View view = LayoutInflater.from(LiteraryCreationActivity.this).inflate(R.layout.layout_popfinish, null);
        RelativeLayout rlBg = view.findViewById(R.id.rl_bg);
        rlBg.getBackground().setAlpha(100);
        TextView tv_back = view.findViewById(R.id.tv_back);
        TextView tv_share = view.findViewById(R.id.tv_share);
        TextView tv_unit = view.findViewById(R.id.tv_unit);
        TextView tv_num = view.findViewById(R.id.tv_num);
        TextView tv_type = view.findViewById(R.id.tv_type);
        if (type == 1088){
            tv_type.setText(message);
            tv_unit.setVisibility(View.GONE);
            tv_num.setVisibility(View.GONE);
        }else {
            tv_unit.setVisibility(View.VISIBLE);
            tv_num.setVisibility(View.VISIBLE);
            tv_type.setText("本次获得" + message + "奖励");
            tv_num.setText(30 + "");
        }
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUserPop.dismiss();
                mUserPop = null;
                Intent intent = new Intent();
                intent.putExtra("ISVIDEO", videoPath);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        tv_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUserPop.dismiss();
                mUserPop = null;
            }
        });
        mUserPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        mUserPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mUserPop.setBackgroundDrawable(new BitmapDrawable());
        mUserPop.setFocusable(true);
        mUserPop.update();
        mUserPop.showAtLocation(view, Gravity.CENTER, 0, 0);
        mUserPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mUserPop.dismiss();
                mUserPop = null;
                initShareHttp();
            }
        });
    }

    private void initShareHttp() {
        RequestParams params = new RequestParams(com.mf.morefun.constant.Configuration.HOST + com.mf.morefun.constant.Configuration.SHARE);
        RequestShareBean requestShareBean = new RequestShareBean();
        requestShareBean.setUserID(mSPutils.getString(com.mf.morefun.constant.Configuration.USERID));
        requestShareBean.setContextID(getIntent().getStringExtra("CONTEXTID"));
        requestShareBean.setContextType(getIntent().getStringExtra("CONTEXTTYPE"));
        requestShareBean.setShareType("2");//1为图片  2为链接
        requestShareBean.setMediaType(getIntent().getStringExtra("MEDIATYPE"));
        params.setBodyContent(JSON.toJSONString(requestShareBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            ShareBean shareBean = JSON.parseObject(resultBean.getResult(), ShareBean.class);
                            try {
                                showSharePop(shareBean);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private PopupWindow sharePop;

    private void showSharePop(ShareBean shareBean) {
        if (sharePop == null) {
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_sharepop, null);
            // 这里启动头像
            RelativeLayout rl_bg = (RelativeLayout) view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            TextView tv_cancel = view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != sharePop) {
                        sharePop.dismiss();
                        sharePop = null;
                    }
                }
            });
            LinearLayout ll_pengyou = view.findViewById(R.id.ll_pengyouquan);
            ll_pengyou.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != sharePop) {
                        sharePop.dismiss();
                        sharePop = null;
                    }
                    if (checkInstalled(0)) {
                        showShare(0, shareBean);
                    } else {
                        ToastUtils.show(LiteraryCreationActivity.this, "请先安装微信", 100);
                    }
                }
            });
            LinearLayout ll_wechat = view.findViewById(R.id.ll_wechat);
            ll_wechat.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != sharePop) {
                        sharePop.dismiss();
                        sharePop = null;
                    }
                    if (checkInstalled(0)) {
                        showShare(1, shareBean);
                    } else {
                        ToastUtils.show(LiteraryCreationActivity.this, "请先安装微信", 100);
                    }
                }
            });
            LinearLayout ll_wechatcollect = view.findViewById(R.id.ll_wechatcollect);
            ll_wechatcollect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != sharePop) {
                        sharePop.dismiss();
                        sharePop = null;
                    }
                    if (checkInstalled(0)) {
                        showShare(2, shareBean);
                    } else {
                        ToastUtils.show(LiteraryCreationActivity.this, "请先安装微信", 100);
                    }
                }
            });
            int h = LiteraryCreationActivity.this.getWindowManager().getDefaultDisplay().getHeight();
            sharePop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, h);
            sharePop.setFocusable(true);
            sharePop.setOutsideTouchable(true);
            sharePop.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                    return false;
                }
            });
            sharePop.setBackgroundDrawable(new BitmapDrawable());
            Rect rect = new Rect();
            LiteraryCreationActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int winHeight = LiteraryCreationActivity.this.getWindow().getDecorView().getHeight();
            sharePop.showAtLocation(LiteraryCreationActivity.this.getWindow().getDecorView(), Gravity.BOTTOM, 0, winHeight - rect.bottom);
        }
    }

    private boolean checkInstalled(int index) {
        boolean isInstall = false;
        switch (index) {
            case 0://微信
                isInstall = isInstallWx("com.tencent.mm");
                break;
            case 1://QQ
                isInstall = isInstallWx("com.tencent.mobileqq");
                break;
        }
        return isInstall;
    }

    /**
     * 是否安装微信
     */
    public boolean isInstallWx(String packageNames) {
        try {
            PackageManager manager = LiteraryCreationActivity.this.getPackageManager();
            List<PackageInfo> list = manager.getInstalledPackages(0);
            List<String> mList = new ArrayList<String>();
            if (null != list && list.size() != 0) {
                for (int i = 0; i < list.size(); i++) {
                    mList.add(list.get(i).packageName);
                }
            }
            if (null != mList && mList.size() != 0) {
                return mList.contains(packageNames);
            } else {
                return false;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return false;
    }

    private void showShare(int index, ShareBean shareBean) {
        if (null != shareBean) {
            UMImage image = new UMImage(LiteraryCreationActivity.this, shareBean.getCover());//资源文件
            String shareUrl = shareBean.getLinkAddress();
            UMWeb web = new UMWeb(shareUrl);
            web.setTitle(shareBean.getContext());//标题
            web.setThumb(image);  //缩略图
            web.setDescription(shareBean.getName());//描述
            switch (index) {
                case 0://朋友群
                    new ShareAction(LiteraryCreationActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                            .withMedia(web).setCallback(shareListener)
                            .share();
                    break;
                case 1://微信
                    new ShareAction(LiteraryCreationActivity.this).setPlatform(SHARE_MEDIA.WEIXIN)
                            .withMedia(web).setCallback(shareListener)
                            .share();
                    break;
                case 2://微信收藏
                    new ShareAction(LiteraryCreationActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_FAVORITE)
                            .withMedia(web).setCallback(shareListener)
                            .share();
                    break;
            }
        }
    }


    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(LiteraryCreationActivity.this, "分享成功", Toast.LENGTH_LONG).show();
            if (!StringUtils.isEmpty(getIntent().getStringExtra("BOOKID"))) {
                mSendStartOrFlowerNet = new SendStarOrFlowerNet(LiteraryCreationActivity.this, lyContent);
                mSendStartOrFlowerNet.initGetFlower(10
                        , mSPutils.getString(com.mf.morefun.constant.Configuration.USERID),
                        getIntent().getStringExtra("BOOKID"),
                        "2", "7"
                );
            }
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(LiteraryCreationActivity.this, "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(LiteraryCreationActivity.this, "取消分享", Toast.LENGTH_LONG).show();

        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0 && resultCode == RESULT_OK) {
            try {
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                Cursor cursor = cr.query(uri, null, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        //得到路径
                        videoPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                        videoName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
                        // 视频缩略图路径：MediaStore.Images.Media.DATA
                        String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                        ivNormal.setVisibility(View.GONE);
                        player.setVisibility(View.VISIBLE);
                        if (!StringUtils.isEmpty(videoPath)) {
                            initPlayer();
                            player.play(videoPath);
                        }
                    }
                    cursor.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.show(getApplicationContext(), "获取不到视频", 100);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initPlayer() {
        player.setLive(false);
        player.setOnNetListener(new OnNetListener() {
            @Override
            public void onIgnoreMobileNet() {
                ignoreNet = true;
            }
        }).setOnPlayerListener(new IPlayerListener() {
            @Override
            public void onLoading() {
                player.getControl().setState(ControlLayout.STATE_LOADING);
            }

            @Override
            public void onCompletion(IMediaPlayer mp) {
                player.getControl().setState(ControlLayout.STATE_COMPLETION);
            }

            @Override
            public void onPrepared(IMediaPlayer mp) {
                //代表移动网
                if (!ignoreNet && NetUtil.getNetWorkState(LiteraryCreationActivity.this) == 0) {
                    player.pause();
                    player.getControl().setState(ControlLayout.STATE_MOBILE_NET);
                } else {
                    player.getControl().setState(ControlLayout.STATE_PREPARED);
                }
            }

            @Override
            public boolean onError(IMediaPlayer mp, int what, int extra) {
                player.getControl().setState(ControlLayout.STATE_ERROR);
                return false;
            }

            @Override
            public boolean onInfo(IMediaPlayer mp, int what, int extra) {
                return false;
            }

            @Override
            public void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sarNum, int sarDen) {

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player != null) {
            player.onResume();
        }
    }

    @Override
    protected void onPause() {
        if (player != null) {
            player.onPause();
        }
        super.onPause();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        ViewGroup.LayoutParams lp = player.getLayoutParams();
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
            player.setLayoutParams(lp);
        } else {
            lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
            player.setLayoutParams(lp);
        }
        if (player != null) {
            player.onConfigurationChanged(newConfig);
        }
    }

    @Override
    public void onBackPressed() {
        if (player != null && player.onBackPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void finish() {
        if (player != null) {
            player.onDestroy();
        }
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != mSendStartOrFlowerNet) {
            mSendStartOrFlowerNet.stopAnim();
        }
    }
}
